﻿


namespace AutoCAD.EntityTools
{
    public static class ExceptionTools
    {
        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="errorFunction"></param>
        public static void HandleEntityToolErrorSend(this Exception ex, string errorFunction)
        {
            ($"[AutoCad.EntityTool]插件[{errorFunction}]发生错误").CadMessage2();
            (ex.StackTrace).CadMessage2(); ;
            (ex.Message).CadMessage2(); ;
            ($"引发异常的方法: {ex.TargetSite}").CadMessage2(); ;
            ($"导致异常的应用程序或对象的名称: {ex.Source}").CadMessage2(); ;
            ("导致当前异常的 Exception 实例:" + ex.InnerException).CadMessage2(); ;
            (ex.Message).CadAlert(); ;

            #region Trace
            System.Diagnostics.Trace.WriteLine(ex.Message);
            System.Diagnostics.Trace.WriteLine(ex.StackTrace);
            System.Diagnostics.Trace.WriteLine("引发异常的方法:" + ex.TargetSite);
            System.Diagnostics.Trace.WriteLine("导致异常的应用程序或对象的名称:" + ex.Source);
            System.Diagnostics.Trace.WriteLine("导致当前异常的 Exception 实例:" + ex.InnerException);
            #endregion
            if (ex.InnerException != null)
            {
                ($"内部异常: {ex.InnerException}").CadMessage2(); ;
            }
        }




























        /// <summary>
        /// 处理实体工具异常
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="errorFunction">发生错误的函数名</param>
        /// <param name="showAlert">是否显示警报对话框</param>
        /// <param name="logToTrace">是否记录到Trace</param>
        public static void HandleEntityToolError(this Exception ex, string errorFunction,
            bool showAlert = true, bool logToTrace = true)
        {
            if (ex == null)
                return;

            if (string.IsNullOrWhiteSpace(errorFunction))
                errorFunction = "未知函数";

            try
            {
                // 构建错误信息
                var errorMessage = BuildErrorMessage(ex, errorFunction);

                // 输出到CAD消息
                OutputToCadMessages(errorMessage, ex);

                // 显示警报
                if (showAlert)
                {
                    ShowAlertMessage(ex, errorFunction);
                }

                // 记录到Trace
                if (logToTrace)
                {
                    LogToTrace(ex , errorMessage);
                }
            }
            catch (Exception handlerEx)
            {
                // 异常处理程序本身出错时的后备处理
                HandleHandlerException(handlerEx);
            }
        }

        /// <summary>
        /// 构建错误消息
        /// </summary>
        public static string BuildErrorMessage(this Exception ex, string errorFunction)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"[AutoCad.EntityTool] -  [{errorFunction}] 发生错误");
            sb.AppendLine($"错误类型: {ex.GetType().Name}");
            sb.AppendLine($"错误消息: {ex.Message}");

            if (ex is Autodesk.AutoCAD.Runtime.Exception acadEx)
            {
                sb.AppendLine($"AutoCAD错误状态: {acadEx.ErrorStatus}");
            }

            if (ex.TargetSite != null)
            {
                sb.AppendLine($"引发异常的方法: {ex.TargetSite.Name}");
            }

            if (!string.IsNullOrEmpty(ex.Source))
            {
                sb.AppendLine($"异常来源: {ex.Source}");
            }

            if (ex.InnerException != null)
            {
                sb.AppendLine($"内部异常: {ex.InnerException.Message}");
            }

            if (!string.IsNullOrEmpty(ex.StackTrace))
            {
                sb.AppendLine($"堆栈跟踪: {ex.StackTrace}");
            }

            return sb.ToString();
        }

        /// <summary>
        /// 输出到CAD消息
        /// </summary>
        public static void OutputToCadMessages(this string errorMessage, Exception ex)
        {
            try
            {
                var doc = Application.DocumentManager.MdiActiveDocument;
                if (doc != null)
                {
                    using (doc.LockDocument())
                    {
                        var editor = doc.Editor;

                        // 输出主要错误信息
                        editor.WriteMessage($"\n[AutoCad.EntityTool]插件错误: {ex.Message}");

                        // 如果是AutoCAD异常，显示额外信息
                        if (ex is Autodesk.AutoCAD.Runtime.Exception acadEx)
                        {
                            editor.WriteMessage($"\nAutoCAD错误状态: {acadEx.ErrorStatus}");
                        }

                        // 只在调试模式下显示详细堆栈
#if DEBUG
                        if (!string.IsNullOrEmpty(ex.StackTrace))
                        {
                            editor.WriteMessage($"\n堆栈跟踪: {ex.StackTrace}");
                        }
#endif
                    }
                }
            }
            catch
            {
                // 忽略输出过程中的错误
            }
        }

        /// <summary>
        /// 显示警报消息
        /// </summary>
        public static void ShowAlertMessage(this Exception ex, string errorFunction)
        {
            try
            {
                // 构建用户友好的警报消息
                string alertMessage = $"[AutoCad.EntityTool]插件发生错误\n\n" +
                                     $"操作: {errorFunction}\n" +
                                     $"错误: {GetUserFriendlyMessage(ex)}";

                // 使用您现有的CadAlert方法
                alertMessage.CadAlert();
            }
            catch
            {
                // 忽略警报显示错误
            }
        }

        ///// <summary>
        ///// 获取用户友好的错误消息
        ///// </summary>
        //private static string GetUserFriendlyMessage(Exception ex)
        //{
        //    if (ex is Autodesk.AutoCAD.Runtime.Exception acadEx)
        //    {
        //        return $"{acadEx.Message} (错误代码: {acadEx.ErrorStatus})";
        //    }

        //    // 常见异常类型的友好消息
        //    return ex switch
        //    {
        //        ArgumentException => "参数错误: " + ex.Message,
        //        InvalidOperationException => "操作无效: " + ex.Message,
        //        IOException => "文件读写错误: " + ex.Message,
        //        UnauthorizedAccessException => "访问被拒绝: " + ex.Message,
        //        TimeoutException => "操作超时: " + ex.Message,
        //        _ => ex.Message
        //    };
        //}

        /// <summary>
        /// 获取用户友好的错误消息
        /// </summary>
        public static string GetUserFriendlyMessage(this Exception ex)
        {
            if (ex is Autodesk.AutoCAD.Runtime.Exception acadEx)
            {
                return $"{acadEx.Message} (错误代码: {acadEx.ErrorStatus})";
            }

            // 使用传统的 switch 语句替代 switch 表达式
            switch (ex)
            {
                case ArgumentException _:
                    return "参数错误: " + ex.Message;
                case InvalidOperationException _:
                    return "操作无效: " + ex.Message;
                case IOException _:
                    return "文件读写错误: " + ex.Message;
                case UnauthorizedAccessException _:
                    return "访问被拒绝: " + ex.Message;
                case TimeoutException _:
                    return "操作超时: " + ex.Message;
                default:
                    return ex.Message;
            }
        }

        /// <summary>
        /// 记录到Trace
        /// </summary>
        public static void LogToTrace(this Exception ex , string errorMessage)
        {
            try
            {
                System.Diagnostics.Trace.WriteLine("=== [AutoCad.EntityTool]插件错误记录 ===");
                System.Diagnostics.Trace.WriteLine($"时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                System.Diagnostics.Trace.WriteLine(errorMessage);
                System.Diagnostics.Trace.WriteLine("========================");

                // 记录到Windows事件日志（可选）
                LogToEventLog(ex);
            }
            catch
            {
                // 忽略日志记录错误
            }
        }

        /// <summary>
        /// 记录到Windows事件日志
        /// </summary>
        public static void LogToEventLog(this Exception ex)
        {
            try
            {
                using (EventLog eventLog = new EventLog("Application"))
                {
                    eventLog.Source = "[AutoCad.EntityTool] AutoCAD插件";
                    eventLog.WriteEntry($"[AutoCad.EntityTool]插件错误: {ex.Message}",
                        EventLogEntryType.Error, 1001);
                }
            }
            catch
            {
                // 忽略事件日志错误
            }
        }

        /// <summary>
        /// 处理异常处理程序本身的异常
        /// </summary>
        public static void HandleHandlerException(this Exception handlerEx)
        {
            try
            {
                System.Diagnostics.Trace.WriteLine($"异常处理程序出错: {handlerEx.Message}");
            }
            catch
            {
                // 终极后备：什么都不做
            }
        }

        /// <summary>
        /// 简化的异常处理扩展方法
        /// </summary>
        public static void HandleSimple(this Exception ex, string context = null)
        {
            try
            {
                var doc = Application.DocumentManager.MdiActiveDocument;
                if (doc != null && ex != null)
                {
                    using (doc.LockDocument())
                    {
                        string message = string.IsNullOrEmpty(context)
                            ? $"错误: {ex.Message}"
                            : $"{context}: {ex.Message}";

                        doc.Editor.WriteMessage($"\n{message}");

#if DEBUG
                        doc.Editor.WriteMessage($"\n堆栈: {ex.StackTrace}");
#endif
                    }
                }
            }
            catch
            {
                // 忽略所有错误
            }
        }
    }
}
